﻿
using System;

namespace MathService.Time
{
    /// <summary>
    /// Измеритель времени
    /// </summary>
    public sealed class TimeCounter
    {
        /// <summary>Флаг состояния</summary>
        private bool f_Started;

        /// <summary>Объект межпотоковой синхронизации</summary>
        private readonly object f_LockObject = new object();

        //private readonly List<TimeEvent> f_Events = new List<TimeEvent>();
        private TimeSpan f_StartTime;
        private TimeSpan f_TotalTime;

        /// <summary>Состояние измерителя</summary>
        public bool IsStarted { get { return f_Started; } set { if(value) Start(); else Stop(); } }

        /// <summary>Прошло времени</summary>
        public TimeSpan TotalTime { get { return f_TotalTime; } }

        /// <summary>Запуск</summary>
        public void Start()
        {
            if(f_Started) return;
            lock(f_LockObject)
            {
                if(f_Started) return;

                f_StartTime = DateTime.Now.TimeOfDay;
                //f_Events.Add(new TimeEvent {StartTime = f_StartTime });

                f_Started = true;
            }
        }

        /// <summary>Остановка</summary>
        public void Stop()
        {
            if(!f_Started) return;
            lock(f_LockObject)
            {
                if(!f_Started) return;

                var now = DateTime.Now.TimeOfDay;
                //f_Events[f_Events.Count - 1].StopTime = now;
                f_TotalTime += now - f_StartTime;


                f_Started = false;
            }
        }

        /// <summary>Сброс измерителя</summary>
        public void Reset()
        {
            lock(f_LockObject)
            {
                f_Started = false;
                f_StartTime = default(TimeSpan);
                f_TotalTime = default(TimeSpan);
            }
        }
    }

    ///// <summary>Структура события времени</summary>
    //sealed class TimeEvent
    //{
    //    /// <summary>Начало события</summary>
    //    public TimeSpan StartTime;

    //    /// <summary>Конец события</summary>
    //    public TimeSpan StopTime;

    //    /// <summary>Длительность</summary>
    //    public TimeSpan TimeLength { get { return StopTime - StartTime; } }
    //}
}
